<?php
class UsersController extends AppController {

	var $name = 'Users';
    var $anonymousAccess = array('login','signup','logout','completed');
    var $uses = array('User','UsersBatch','Part','Question','Answer','Batch');

	function index() 
    {		
	
	}
    
    //where test forms will be sumitted
    function test_submit($type=null)
    {   
        if (!empty($this->data)) {
            
            //set the current part id
            $batch = $this->UsersBatch->getBatch($this->Session->read('User.id'));
            $this->UsersBatch->setCurrentPartId($batch,$this->data['test']['part_id']);       

            //get the batch details and part            
            $part =  $this->Part->read(null,$this->data['test']['part_id']);
            $batch = $this->UsersBatch->getBatch($this->Session->read('User.id'));
            
            $total_mark = 0;
            
            //check for valid submit. - time expire and type
            if($part['Part']['type']=='options')
            {
                if($this->UsersBatch->isNotExpired($batch['UsersBatch']['session1_start_time'],$this->settings['session1_time_limit']))
                {
                    //debug($this->params);
                    $answers = $this->params['form']['question'];                    
                    foreach($answers as $question_id=>$answer)
                    {
                        $question = $this->Question->getQuestion($question_id);
                        $this->Answer->create();
                        $record = array();
                        $record['Answer']['question_id'] = $question_id;
                        $record['Answer']['user_id'] = $this->Session->read('User.id');
                        $record['Answer']['answer'] = $answer;
                        if($question['Question']['answer'] == $answer)
                        {
                            $record['Answer']['mark'] = $question['Question']['mark'];    
                        }
                        else{
                            $record['Answer']['mark'] = 0;
                        }
                        $this->Answer->save($record);
                        $total_mark = $total_mark + $record['Answer']['mark']; 
                    }
                }
                else
                {
					$batch = $this->UsersBatch->getBatch($this->Session->read('User.id'));
                    $this->UsersBatch->setCompleted($this->Session->read('User.id'),$batch['UsersBatch']['batch_id']);
                    $this->redirect('/users/error/timeExpired');  
                }
            }
            elseif($part['Part']['type']=='essay')
            {
                //mark whole batch as completed
                $this->UsersBatch->endSession2AndSetCompleted($this->Session->read('User.id'),$batch['UsersBatch']['batch_id']);
				$answers = $this->params['form']['question'];   
				foreach($answers as $question_id=>$answer){					
					$this->Answer->create();
					$record = array();
					$record['Answer']['question_id'] = $question_id;
					$record['Answer']['user_id'] = $this->Session->read('User.id');
					$record['Answer']['answer'] = $answer;				
					$record['Answer']['mark'] = 0;				
					$this->Answer->save($record);
                }
				$this->redirect('/users/completed/'.$type);
            }          
             
            //calculate total marks
            /*if($total_mark<$part['Part']['min_mark'])
            {
                $this->UsersBatch->endSession1AndSetCompleted($this->Session->read('User.id'),$batch['UsersBatch']['batch_id']);
                $this->UsersBatch->setCompleted($this->Session->read('User.id'),$batch['UsersBatch']['batch_id']);                
                $this->redirect('/users/error/failed'); exit;
            }*/            
            
            //if next  part is essay type then redirect to marks page.
            if($nextPart = $this->Part->getNextPart($batch['UsersBatch']['current_part_id'],$batch['UsersBatch']['batch_id'],'essay'))
            {
               //debug($nextPart);
                if($nextPart['Part']['type']=='essay')
                {
                    
                    $this->UsersBatch->endSession1AndSetCompleted($batch['UsersBatch']['user_id'],$batch['UsersBatch']['batch_id']);
                    $this->redirect('/users/marks');
                }
            }
            
            $this->redirect('/users/test');
        }
    }
    
    //where all necessary processes are done for tests.. 
    function test()
    {        
        //if no session then redirect to error page.
        if($this->Session->read('User.id')=='')
        {            
            $this->redirect('/users/error/invalidSession'); exit;
        }
        
        //get the batch. if not assigned then assign it.
        $batch = $this->UsersBatch->getAndAssignBatch($this->Session->read('User.id'));
        
        //if no batch then redirect to error page.
        if(count($batch)==0)
        {
            $this->redirect('/users/error/noBatchAllocated'); exit;
        }
                
        //if essay session is starting
        $nextPart = $this->Part->getNextPart($batch['UsersBatch']['current_part_id'],$batch['UsersBatch']['batch_id'],'essay');        
        if($nextPart['Part']['type']=='essay' && $batch['UsersBatch']['session2_start_time'] == '0000-00-00 00:00:00'){                   
            $this->UsersBatch->startSession2($batch['UsersBatch']['user_id'],$batch['UsersBatch']['batch_id']);
            $batch = $this->UsersBatch->getBatch($this->Session->read('User.id'));
        }
        
        //if it is a valid session
        if($diff = $this->UsersBatch->isValidSession($batch,$this->settings['session1_time_limit'],$this->settings['session2_time_limit']))
        {             
            //debug($diff);
            $this->set('diff',$diff);
            //if last session is set then..
            if(isset($diff['diff_2']))
            {
                $nextPart = $this->Part->getLastPart($batch['UsersBatch']['batch_id']);
               
                $this->set('part',$nextPart);
            }
            else 
            {
                //go to next part..
                if($nextPart = $this->Part->getNextPart($batch['UsersBatch']['current_part_id'],$batch['UsersBatch']['batch_id']))
                {
                    $this->set('part',$nextPart);        
                }
                else //if all parts are completed then..
                {
                    //mark as completed and redirect to completed page.
                    $this->UsersBatch->updateSession1Completed($batch['UsersBatch']['user_id'],$batch['UsersBatch']['batch_id']);
                    $this->redirect('/users/marks');        
                }                
            }
        }
        else
        {
            $this->redirect('/users/error/timeExpired');    
        }
    }
    
    //final page
    function completed($type='')
    {
		if($type=='') $type = 'completed_message';
		else $type = 'timeup_message';
		$this->set('message',$this->settings[$type]); //timeup_message
        $this->Session->destroy();
    }
    
    //scores will be shown here
    function marks()
    {
		list($totals,$parts,$failed,$fulltotal) = $this->calculatMarks($this->Session->read('User.id'));
					
		if($failed==true)
		{
			$this->UsersBatch->endSession1AndSetCompleted($this->Session->read('User.id'),$batch['UsersBatch']['batch_id']);
			$this->UsersBatch->setCompleted($this->Session->read('User.id'),$batch['UsersBatch']['batch_id']);                
			$this->redirect('/users/error/failed'); exit;		
		}
		
		$this->set('fulltotal', $fulltotal);	
		$this->set('totals',$totals);		
		$this->set('parts',$parts);
    }
	
   
    //unauthorized access
    function error($errorType = '')
    {		
		switch($errorType)
		{
			case 'timeExpired':
				$error = $this->settings['error_msg_time_expire'];
			break;
			
			case 'failed':
				$error = $this->settings['error_msg_failed'];
			break;
			
			case 'invalidSession':
				$error = $this->settings['your session expired!'];
			break;
			
			case 'noBatchAllocated':
				$error = $this->settings['error_msg_nobatch'];
			break;
			
			default:
				$error = $this->settings['your session expired!'];
			break;
		}
		$this->Session->destroy();
		$this->set('error',$error);
    }
    
    function signup()
    {
		if (!empty($this->data)) {
			$this->User->create();
			if ($data = $this->User->save($this->data)) {
				//$this->Session->setFlash(__('The user has been saved', true));
                $this->Session->write('User',$data['User']);
                $this->Session->write('User.id',$this->User->id);
				$this->redirect(array('action' => 'index'));                
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
        
    }

    function logout()
    {
        //$this->Session->destroy();
        $this->redirect('/');
    }
	
    function login()
	{	   
	   if(!empty($this->data))
       {             
           if($data = $this->User->login($this->settings['login_method'],$this->data['User']['username'],$this->data['User']['password']))
           {            
              $this->Session->write('User',$data['User']);			  
              $this->Session->write('User.permissions',$data['permissions']); 			 
              $this->redirect('/admin/batches/index');
           }    
           else
           {
             $this->Session->setFlash(__('Username/password may be wrong.',true),true);
             $this->redirect('/users/login');
             exit(0);
           }
       }
	}
    
	function admin_logout()
    {
        //$this->Session->destroy();
        $this->redirect('/');
    }	
	
	function admin_change_password()
	{
		if(!empty($this->data))
		{ 
			if(($this->data['User']['confirm_password'] == $this->data['User']['password']) && $this->data['User']['password']!='')
			{
				$this->User->changePassword($this->Session->read('User.id'),$this->data['User']['password']);
				$this->Session->setFlash('Password has been changed successfully.',true);
				$this->redirect('/admin/users/change_password');
			}
			else
			{
				$this->Session->setFlash('Passwords should be same',true);
				$this->redirect('/admin/users/change_password');
			}
		}
	}

	function admin_config()
	{
		if(!empty($this->data))
		{ 
			foreach($this->data['SiteSetting'] as $var=>$value)
			{
				$this->SiteSetting->updateVar($var,$value);
			}
			$this->Session->setFlash(__('Configurations updated.',true),true);
            $this->redirect('/admin/users/config');
		}
	
		$this->set('settings',$this->SiteSetting->getAll(true));
	}        
	
	function admin_index($type='waiting') {
		$this->User->recursive = 0;
		$this->paginate['User'] = array('conditions'=>array('User.test_status'=>$type));
		$this->set('users', $this->paginate('User'));
	}

	function admin_view($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		
		if(isset($this->params['form']['passed']))
		{
			$this->User->changeTestStatus($id,'passed');
			$this->Session->setFlash(__('User has been passed.',true),true);
			$this->redirect('/admin/users/index');
		}
		elseif(isset($this->params['form']['failed']))
		{
			$this->User->changeTestStatus($id,'failed');
			$this->Session->setFlash(__('User has been failed.',true),true);
			$this->redirect('/admin/users/index');		
		}
		
		list($totals,$parts,$failed,$fulltotal,$batch) = $this->calculatMarks($id);
		$essayPart = $this->Part->getAllParts($batch['UsersBatch']['batch_id'],'essay');
//		debug($parts);		
		$this->set('totals', $totals);
		$this->set('parts', $parts);
		$this->set('failed', $failed);	
		$this->set('fulltotal', $fulltotal);	
		$this->set('user', $this->User->read(null, $id));
		$this->set('essayPart',$essayPart);
		$this->set('essayAnswer', $this->Answer->getEssayAnswer($id,$essayPart['Question'][0]['id']));
	}

	function admin_add() {
		if (!empty($this->data)) {
			$this->User->create();
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The user has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
	}

	function admin_edit($id = null) {
		if (!$id && empty($this->data)) {
			$this->Session->setFlash(__('Invalid user', true));
			$this->redirect(array('action' => 'index'));
		}
		if (!empty($this->data)) {
			if ($this->User->save($this->data)) {
				$this->Session->setFlash(__('The user has been saved', true));
				$this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.', true));
			}
		}
		if (empty($this->data)) {
			$this->data = $this->User->read(null, $id);
		}
	}

	function admin_delete($id = null) {
		if (!$id) {
			$this->Session->setFlash(__('Invalid id for user', true));
			$this->redirect(array('action'=>'index'));
		}
		if ($this->User->delete($id)) {
			$this->Session->setFlash(__('User deleted', true));
			$this->redirect(array('action'=>'index'));
		}
		$this->Session->setFlash(__('User was not deleted', true));
		$this->redirect(array('action' => 'index'));
	}
}
